/*
 * DA2.c
 *  Author: Henry
 */ 
#include <avr/io.h>
#include <avr/interrupt.h>
void delay(void);

int main(void)
{
	DDRB = 0xFF;		//Set PORTB to output
	DDRC = 0xFF;		//Set PORTC to output
	DDRD = 0x04;		//Set Port.D2(INT0) to input
	PORTB = 0x00;		//Initialize PORTB to 0
	PORTC = 0x00;		//Initialize PORTC to 0
	TCNT0 = 0x00;		//Initialize Timer0

	EIMSK = (1 << INT0);	//Enable INT0 Interrupt
	EICRA = (1 << ISC01);	//Falling Edge of INT0 generates interrupt request
	sei();
    while(1)
    {
		PORTB = TCNT0;			//Output 8-bit Counter to PORTB
		delay();				//elapse 0.25s
		if((PORTC && (1 << 0)) == 0)	//If wave is falling edge
		TCNT0++;				//Increment Count
		if(TCNT0%10 == 0)		//If this is a 10th falling edge
		PORTC ^= (1 << 1);		//Toggle 9th LED
		if(TCNT2%2 == 0)		//If this is 2nd falling edge of 9th LED
		PORTC ^= (1 << 2);		//Toggle the 10th LED
    }
}
ISR(INT0_vect){
	TCNT2++;
}
void delay(){
	TCNT1H = 0xF0;			//Set Timer1 count value to 61630
	TCNT1L = 0xBE;			//for delay of 0.25s
	TCCR1A = 0x00;			//Set Timer1 mode to Normal mode
	TCCR1B = (1 << CS11) | (1 << CS10);	//64 Prescalar
	while((TIFR1 & (1<<TOV1)) == 0){} //Run for 0.25s
	TCCR1A = 0x00;			//Stop Timer1
	TCCR1B = 0x00;
	PORTC = PORTC^(1 << 0);		//Toggle PORTC.0
	TIFR1 = 1<<TOV1;		//Reset flag register
}